/* 
 * This program is free software; you can redistribute it and/or modify 
 * it under the terms of the GNU General Public License as published by 
 * the Free Software Foundation; either version 3 of the License, or 
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but 
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 
 * for more details.
 * 
 * You should have received a copy of the GNU General Public License along 
 * with this program; if not, write to the Free Software Foundation, Inc., 
 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */

#include <QVariant>
#include <QFile>
#include <QFileInfo>
#include <QRegExp>
#include "karehaagent.h"
#include "log.h"
#include "components/chan.h"
#include "components/board.h"
#include "karehatasksendpost.h"


namespace Wishmaster
{
	KarehaAgent::KarehaAgent(const QString& host) : DefaultAgent(host),
		m_host(host)
	{

	}

	KarehaAgent::~KarehaAgent()
	{
	}

	void KarehaAgent::makePost(const PostDescriptor& post, const QString& captcha)
	{
		TaskPtr task = TaskPtr(new KarehaTaskSendPost(post, captcha, requestManager(), QString("Sending post"), this));
		connect(task.data(), SIGNAL(result(KarehaTaskSendPost*, QByteArray,QString)), this, SLOT(resultPost(KarehaTaskSendPost*, QByteArray,QString)));

		taskhub()->queueTask(task);
	}

	void KarehaAgent::createThread(const PostDescriptor& post, const QString& captcha)
	{
		TaskPtr task = TaskPtr(new KarehaTaskSendPost(post, captcha, requestManager(), QString("Creating thread"), this));
		connect(task.data(), SIGNAL(result(KarehaTaskSendPost*, QByteArray,QString)), this, SLOT(resultPost(KarehaTaskSendPost*, QByteArray,QString)));

		taskhub()->queueTask(task);
	}

	void KarehaAgent::deleteThread(const ThreadId& /*threadId*/, const QString& /* password */)
	{
		// Not implemented yet
	}

	void KarehaAgent::deletePost(const PostId& /*postId*/, const QString& /* password */)
	{
	}

	void KarehaAgent::resultPost(KarehaTaskSendPost* task, const QByteArray& data, const QString& contentType)
	{
		QString regexp = QString::fromUtf8("<body class=\"errorpage\">.*<h1>([^<>]*)");
		QRegExp rx(regexp);
		if(rx.indexIn(QString::fromUtf8(data)) != -1)
		{
			log(llDebug, "Error: %s", qPrintable(rx.cap(1)));
			emit postingError(rx.cap(1));
			return;
		}
		else
		{
			//emit postingError("");
			// TODO we can emit here 'thread' slot as well
		}
		emit postingDone(task->threadId());
	}

	QStringList KarehaAgent::ratings()
	{
		return QStringList();
	}

	ChanAgent* KarehaAgent::clone(const QString& host)
	{
		return new KarehaAgent(host);
	}

	QString KarehaAgent::id()
	{
		return "kareha";
	}
}

Q_EXPORT_PLUGIN2(karehaagent, Wishmaster::KarehaAgent)

